package com.jp.knowledge.fragment;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.ImageActivity;
import com.jp.knowledge.adapter.ProductUIAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.ProductUIModel;
import com.jp.knowledge.model.ProductVersion;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.my.model.CollectionUiModel;
import com.jp.knowledge.refresh.JpRefreshView;
import com.jp.knowledge.util.ResultSubscriber;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author jiayen     2017-06-09 17:17:07
 */
public class ProduceUIFragment extends BaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, ResultSubscriber.OnResultListener {

    private View  mView;
    private static final int REFRESH_DATA_LIST_CODE = 0x02;
    private static final int LOAD_MODE_DATA_LSIT_CODE = 0x03;


    @ViewInject(R.id.refresh)
    private CanRefreshLayout refreshLayout;
    @ViewInject(R.id.can_content_view)
    private RecyclerView refreshContent;
    @ViewInject(R.id.can_refresh_footer)
    private JpRefreshView refreshFooter;

    private List<ProductUIModel> productUIModelList;
    private ProductUIAdapter productUIAdapter;
    private ArrayList<String> medias;
    private StaggeredGridLayoutManager gridLayoutManager;

    private String productInterfaceDataCachePaht;
    private FileCacheManager cacheManager;

    private LocalBroadcastManager localBroadcastManager;
    private LocalBroadCast localBroadCast;

    private int action;
    private int page=1;
    private String tagId;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(mView == null) {
            mView = inflater.inflate(R.layout.fragment_produce_ui, container, false);
            x.view().inject(this, mView);
            init();
        }
        return mView;
    }

    /***
     * 获取intent
     * @return
     */
    private Intent  getIntent(){
        return ((Activity)mContext).getIntent();
    }
    protected void init() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshContent.setHasFixedSize(true);

        action = getIntent().getIntExtra("action",1);
        gridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        gridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        refreshContent.setLayoutManager(gridLayoutManager);
        refreshContent.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                gridLayoutManager.invalidateSpanAssignments();
            }
        });

        initBroadcast();
        medias = new ArrayList<>();
        productUIModelList = new ArrayList<>();
        productUIAdapter = new ProductUIAdapter(mContext, productUIModelList, getIntent().getBooleanExtra("isIcon", false));
        refreshContent.setAdapter(productUIAdapter);
        productUIAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
//                Intent intent = new Intent(mContext, PhotoActivity.class);
//                intent.putExtra("position",position);
//                intent.putExtra("imgs",medias);
//                startActivity(intent);
                ImageActivity.startActivity(mContext, position, action, productUIModelList);
            }
        });

        productInterfaceDataCachePaht = mContext.getCacheDir() + "/productInterfaceContentData_" + action + ".dat";
        cacheManager = new FileCacheManager();

        readProductInterfaceData();
    }

    private void initBroadcast() {
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                for(ProductUIModel uiModel : productUIModelList)
                    if(uiModel.getId().equals(intent.getStringExtra("id"))){
                        uiModel.setIsFollow(intent.getIntExtra("isCollection", 0));
                        productUIAdapter.updateAdapter(productUIModelList);
                        return;
                    }
            }
        });
        localBroadcastManager.registerReceiver(localBroadCast, new IntentFilter(LocalBroadCast.DETAIL_SC_BROAD));;
    }

    @Override
    public void onDestroy() {
        localBroadcastManager.unregisterReceiver(localBroadCast);
        List<ProductUIModel> productUIModels = new ArrayList<>();
        if(productUIModelList.size() <= 20){
            productUIModels.addAll(productUIModelList);
        } else{
            for(int  i = 0; i < 20; i++)
                productUIModels.add(productUIModelList.get(i));
        }
        saveCache(productUIModels, productInterfaceDataCachePaht);
        super.onDestroy();
    }


    private void readProductInterfaceData(){
        Observable.create(new Observable.OnSubscribe<List<ProductUIModel>>() {
            @Override
            public void call(Subscriber<? super List<ProductUIModel>> subscriber) {
                List<ProductUIModel> data = (List<ProductUIModel>) cacheManager.readObject(productInterfaceDataCachePaht);
                subscriber.onNext(data);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<ProductUIModel>>() {
                    @Override
                    public void onCompleted() {
                        if(productUIAdapter.getItemCount() > 0)
                            onRefresh();
                        else
                            refreshLayout.autoRefresh();
                    }
                    @Override
                    public void onError(Throwable e) {
                        onCompleted();
                    }
                    @Override
                    public void onNext(List<ProductUIModel> data) {
                        if(data != null) {
                            productUIModelList = data;
                            productUIAdapter.updateAdapter(productUIModelList);
                            medias.clear();
                            for(CollectionUiModel model : productUIModelList){
                                medias.add(model.getCover()+"?imageMogr2/format/jpg");//标清图片
                            }
                        }
                        onCompleted();
                    }
                });
    }

    private void saveCache(final Object data, final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(data, path);
            }
        }).start();
    }

    public void autoRefresh(String tagId){
        this.tagId = tagId;
        if(mView != null) {
            refreshContent.scrollToPosition(0);
            refreshLayout.autoRefresh();
        }
    }

    @Override
    public void onRefresh() {
        getProductInterfaceData(REFRESH_DATA_LIST_CODE);
    }

    @Override
    public void onLoadMore() {
        if(!refreshFooter.isLoadComplete())
            getProductInterfaceData(LOAD_MODE_DATA_LSIT_CODE);
        else
            refreshLayout.loadMoreComplete();
    }


    private void getProductInterfaceData(int mode){
       boolean product = getIntent().getBooleanExtra("product",false);

        JsonObject param = new JsonObject();
        if(mode == REFRESH_DATA_LIST_CODE) {
            page=1;
            param.addProperty("mode", 0);

        } else{
            page++;
            param.addProperty("mode", 1);
//            if(productUIModelList.size() == 0)
//                param.addProperty("time", System.currentTimeMillis());
//            else
//                param.addProperty("time", productUIModelList.get(productUIModelList.size()-1).getCreatetime());
        }
        if(product) {
            ProductVersion version = (ProductVersion) getIntent().getSerializableExtra("product_data");//说明是产品点击过来的界面
            param.addProperty("id",version.getId());
//            param.addProperty("verId",version.getVersion());
        }
        param.addProperty("page",page);
        if(tagId != null)
            param.addProperty("tagId", tagId);

        param.addProperty("action",action);
        HttpHelper.getInstance(mContext).discoverInterfaceList(param, mode, this);
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
        if(requestType == REFRESH_DATA_LIST_CODE)
            refreshLayout.refreshComplete();
        else if(requestType == LOAD_MODE_DATA_LSIT_CODE)
            refreshLayout.loadMoreComplete();
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
        }  else if(requestType == REFRESH_DATA_LIST_CODE || requestType == LOAD_MODE_DATA_LSIT_CODE){
            if(requestType == REFRESH_DATA_LIST_CODE) {
                productUIModelList.clear();
                refreshFooter.setLoadComplete(false);
            }
            List<ProductUIModel> productUIModels = data.getList(ProductUIModel.class);
            if(productUIModels != null && productUIModels.size() > 0)
                productUIModelList.addAll(productUIModels);
            else if(requestType == LOAD_MODE_DATA_LSIT_CODE)
                refreshFooter.setLoadComplete(true);
            productUIAdapter.updateAdapter(productUIModelList);

            medias.clear();
            for(CollectionUiModel model : productUIModelList){
                medias.add(model.getCover()+"?imageView2/1/interlace/1/format/jpg");
            }
        }
    }

}
